package com.campus.common.util;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 收益计算工具类
 * 用于计算配送员、平台和商户的收益分配
 */
public class ProfitCalculator {
    
    /**
     * 计算各方收益
     * 
     * @param actualPay 实付金额
     * @param deliveryFee 配送费
     * @param deliveryCommissionRate 配送抽成比例
     * @param serviceFeeRate 服务费抽成比例
     * @return 收益计算结果
     */
    public static ProfitResult calculateProfit(BigDecimal actualPay, BigDecimal deliveryFee, 
                                             BigDecimal deliveryCommissionRate, BigDecimal serviceFeeRate) {
        if (actualPay == null || deliveryFee == null || deliveryCommissionRate == null || serviceFeeRate == null) {
            throw new IllegalArgumentException("计算收益的参数不能为空");
        }
        
        // 配送员收益 = 配送费 × (1 - 配送抽成比例)
        BigDecimal deliveryProfit = deliveryFee.multiply(BigDecimal.ONE.subtract(deliveryCommissionRate))
                .setScale(2, RoundingMode.FLOOR); //舍弃精度之后的小数，保证微信分账成功
        
        // 平台收益 = (配送费 × 配送抽成比例) + (实付金额 - 配送费) × 服务费抽成比例
        BigDecimal platformProfit = deliveryFee.multiply(deliveryCommissionRate)
                .add(actualPay.subtract(deliveryFee).multiply(serviceFeeRate))
                .setScale(2, RoundingMode.FLOOR); //舍弃精度之后的小数，保证微信分账成功
        
        // 商户收益 = 实付金额 - 配送员收益 - 平台收益
        BigDecimal merchantProfit = actualPay.subtract(deliveryProfit).subtract(platformProfit)
                .setScale(2, RoundingMode.HALF_UP);
        
        return new ProfitResult(deliveryProfit, platformProfit, merchantProfit);
    }
    
    /**
     * 收益计算结果
     */
    public static class ProfitResult {
        private final BigDecimal deliveryProfit;  // 配送员收益
        private final BigDecimal platformProfit;  // 平台收益
        private final BigDecimal merchantProfit;  // 商户收益
        
        public ProfitResult(BigDecimal deliveryProfit, BigDecimal platformProfit, BigDecimal merchantProfit) {
            this.deliveryProfit = deliveryProfit;
            this.platformProfit = platformProfit;
            this.merchantProfit = merchantProfit;
        }
        
        public BigDecimal getDeliveryProfit() {
            return deliveryProfit;
        }
        
        public BigDecimal getPlatformProfit() {
            return platformProfit;
        }
        
        public BigDecimal getMerchantProfit() {
            return merchantProfit;
        }
    }
}